package com.henu.engineer.controller.teacher

import com.alibaba.fastjson.JSONObject
import com.henu.engineer.StringUtils
import com.henu.engineer.service.LoginService
import com.henu.engineer.service.UserService
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.web.bind.annotation.*

/**
 *
 * @author noexcept
 * @since 2021/8/24 16:20
 */
@RestController
@RequestMapping("/tc")
class TeacherInfoController {

    @Autowired
    lateinit var userService: UserService

    @Autowired
    lateinit var loginService: LoginService

    @GetMapping("/info")
    fun getTeacherInfo(): String {
        val res = JSONObject()
        val teacher = userService.getTeacherInfo()
        return if (teacher != null) {
            res["code"] = 1
            res["msg"] = "success"
            res["res"] = teacher
            res.toJSONString()
        } else {
            res["code"] = 0
            res["msg"] = "failed"
            res["res"] = teacher
            res.toJSONString()
        }
    }

    @PostMapping("/info")
    fun updateContactAndIdentity(@RequestBody jsonObject: JSONObject?): String {
        val res = JSONObject()
        res["code"] = 1
        if (jsonObject == null) {
            res["code"] = 0
            res["msg"] = "parameters are incomplete"
            return res.toJSONString()
        }
        val contact = jsonObject["contact"] as String?
        val identity = jsonObject["identity"] as String?
        if (StringUtils.isEmpty(contact, identity)) {
            res["code"] = 0
            res["msg"] = "parameters are incomplete"
            return res.toJSONString()
        }
        if (!userService.updateContact(contact!!, UserService.TEACHER)) {
            res["msg1"] = "update contact failed"
        }
        if (!userService.updateTeacherIdentity(identity!!))
            res["msg2"] = "update identity failed"
        if (res["msg1"] == null && res["msg2"] == null)
            res["msg"] = "success"
        else
            res["msg"] = "failed"
        return res.toJSONString()
    }

    @PostMapping("/updatePwd")
    fun updatePwd(@RequestBody jsonObject: JSONObject?): String {
        val res = JSONObject()
        if (jsonObject == null) {
            res["code"] = 0
            res["msg"] = "json parameter parse error"
            return res.toJSONString()
        }
        val oldPwd = jsonObject["oldPwd"] as String?
        val newPwd = jsonObject["newPwd"] as String?
        if (StringUtils.isEmpty(oldPwd, newPwd)) {
            res["code"] = 0
            res["msg"] = "parameters are incomplete"
            return res.toJSONString()
        }
        val s = userService.updatePwd(loginService.currentUserId!!, oldPwd!!, newPwd!!)
        res["msg"] = s
        if (s != "SUCCESS")
            res["code"] = 0
        else res["code"] = 1
        return res.toJSONString()
    }
}